package dao

import (
	"github.com/go-xorm/xorm"

	"im/errcode"
	"im/model"
	"im/requests"
	"im/service/orm"
)

type InternalMails struct {
	db *xorm.Engine
}

func NewInternalMailsDao() *InternalMails {
	return &InternalMails{db: orm.GetDB()}
}
func (d InternalMails) ListBy(userId int64, param requests.GetInternalMails) ([]model.InternalMails, int64, error) {
	var (
		rows  = []model.InternalMails{}
		count int64
		err   error
	)
	count, err = d.db.Where("user_id=?", userId).Where("read_status=?",param.ReadStatus).Where("hidden_status=?", model.InternalMails_Show).OrderBy("id desc").Limit(param.Limit, param.GetOffset()).FindAndCount(&rows)
	if err != nil {
		return rows, count, errcode.NewError(errcode.DaoFailed,err)
	}
	return rows, count, nil
}
func (d InternalMails) HideAllRead(userId int64) error {
	var m = model.InternalMails{
		HiddenStatus: model.InternalMails_Hidden,
	}
	_, err := d.db.Where("user_id=?", userId).Where("read_status=?", model.InternalMails_ReadAlready).Update(&m)
	if err != nil {
		return errcode.NewError(errcode.DaoFailed,err)
	}
	return nil
}
func (d InternalMails) ReadReceipt(userId int64, mailIdList ...[]int64) error {
	var m = model.InternalMails{
		ReadStatus: model.InternalMails_ReadAlready,
	}
	var mailIdListInterface = make([]interface{}, len(mailIdList))
	for i, d := range mailIdList {
		mailIdListInterface[i] = d
	}
	_, err := d.db.Where("user_id=?", userId).Where("read_status=?", model.InternalMails_NotRead).In("id", mailIdListInterface...).Update(&m)
	if err != nil {
		return errcode.NewError(errcode.DaoFailed,err)
	}
	return err
}

func (d InternalMails) ReadAllUnread(userId int64) error {
	var m = model.InternalMails{
		ReadStatus: model.InternalMails_ReadAlready,
	}
	_, err := d.db.Where("user_id=?", userId).Where("read_status=?", model.InternalMails_NotRead).Update(&m)
	if err != nil {
		return errcode.NewError(errcode.DaoFailed,err)
	}
	return err
}
func (p InternalMails) Insert(pp model.InternalMails) (int64, error) {
	_, err := p.db.InsertOne(&pp)
	if err != nil {
		return 0, errcode.NewError(errcode.DaoFailed,err)
	}
	return pp.Id, err
}
